package com.example.service.impl;

import com.example.model.entity.ContactForm;
import com.example.service.EmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.time.format.DateTimeFormatter;

/**
 * 邮件服务实现类
 */
@Service
public class EmailServiceImpl implements EmailService {
    
    private static final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    private final JavaMailSender mailSender;
    
    @Value("${spring.mail.username}")
    private String sender;
    
    @Value("${notification.email.receiver}")
    private String receiver;
    
    @Value("${notification.email.subject}")
    private String emailSubject;
    
    public EmailServiceImpl(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }
    
    @Override
    public boolean sendContactFormNotification(ContactForm contactForm) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            
            helper.setFrom(sender);
            helper.setTo(receiver);
            helper.setSubject(emailSubject);
            
            // 构建邮件内容
            String content = buildEmailContent(contactForm);
            helper.setText(content, true);
            
            // 发送邮件
            mailSender.send(message);
            logger.info("联系表单通知邮件发送成功，表单ID: {}", contactForm.getId());
            return true;
        } catch (MessagingException e) {
            logger.error("发送联系表单通知邮件失败: ", e);
            return false;
        }
    }
    
    /**
     * 构建邮件内容
     */
    private String buildEmailContent(ContactForm contactForm) {
        StringBuilder builder = new StringBuilder();
        builder.append("<html><body>");
        builder.append("<h2>新的网站咨询信息</h2>");
        builder.append("<hr/>");
        builder.append("<table border='0' cellspacing='0' cellpadding='0' style='width: 100%; border-collapse: collapse;'>");
        
        // 添加表单信息
        appendTableRow(builder, "姓名", contactForm.getName());
        appendTableRow(builder, "邮箱", contactForm.getEmail());
        
        if (contactForm.getCompany() != null && !contactForm.getCompany().isEmpty()) {
            appendTableRow(builder, "公司/地址", contactForm.getCompany());
        }
        
        if (contactForm.getPhone() != null && !contactForm.getPhone().isEmpty()) {
            appendTableRow(builder, "电话", contactForm.getPhone());
        }
        
        appendTableRow(builder, "主题", contactForm.getSubject());
        appendTableRow(builder, "内容", contactForm.getMessage().replace("\n", "<br/>"));
        appendTableRow(builder, "提交时间", contactForm.getCreatedAt().format(DATE_FORMATTER));
        
        builder.append("</table>");
        builder.append("<hr/>");
        builder.append("<p>此邮件由系统自动发送，请勿回复。</p>");
        builder.append("</body></html>");
        
        return builder.toString();
    }
    
    /**
     * 添加表格行
     */
    private void appendTableRow(StringBuilder builder, String label, String value) {
        builder.append("<tr>");
        builder.append("<td style='padding: 8px; background-color: #f2f2f2; width: 120px;'><strong>").append(label).append(":</strong></td>");
        builder.append("<td style='padding: 8px;'>").append(value).append("</td>");
        builder.append("</tr>");
    }
} 